package com.itheima.reggie.controller;

import com.itheima.reggie.commons.R;
import com.itheima.reggie.pojo.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Api(tags ="地址")
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController extends BaseController {
    @Autowired
    private AddressBookService addressBookService;

    @PostMapping
    public R<AddressBook> saveBook(@RequestBody AddressBook addressBook) {
        //从会话域中获取当前登录的用户id
        Long userId = getLoginIdFromSession();
        //给用户id赋值
        addressBook.setUserId(userId);
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }
    @GetMapping("/list")
    public R<List<AddressBook>> findAddresses(){
        //从会话域中获取当前登录的用户id
        Long userId = getLoginIdFromSession();
        //调用业务层查询当前用户的地址
        List<AddressBook> addressList = addressBookService.queryAddressList(userId);
        return R.success(addressList);
    }
    @PutMapping("/default")
    public R<String> updateDefaultAddress(@RequestBody AddressBook addressBook){
        Long user_id = getLoginIdFromSession();
        addressBook.setUserId(user_id);
        addressBookService.updateDefaultAddress(addressBook);
        return R.success("设置默认地址成功");
    }
    @GetMapping("/default")
    public R<AddressBook> findDefaultAddress(){
        Long userId = getLoginIdFromSession();
        AddressBook defaultAddress = addressBookService.getDefaultAddress(userId);
        return R.success(defaultAddress);
    }
    @GetMapping("/{id}")
    public R<AddressBook> getById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook == null){
            return R.error("没有找到该地址");
        }
        return R.success(addressBook);
    }
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        addressBookService.updateAddress(addressBook);
        return R.success("修改成功");
    }


    @DeleteMapping
    public R<String> deleteById(Long ids){
        addressBookService.deleteById(ids);
        return R.success("删除成功");
    }

}
